package com.test.ssm.controller;

import com.test.ssm.pojo.HostIp;
import com.test.ssm.service.HostService;
import com.test.ssm.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class HostController {
    @Autowired
    private HostService hostService;

    @RequestMapping("go_update.html")
    public String goUpdate(Integer id, Model model) {
        HostIp hostIp = hostService.getHostById(id);
        model.addAttribute("host", hostIp);
        return "update.jsp";
    }

    @RequestMapping("update.html")
    public String update(HostIp hostIp, Model model) {
        Map<String, Object> result = checkData(hostIp);
        if ((boolean) result.get("status")) {
            hostService.updateHost(hostIp);
            return "redirect:list.html";
        } else {
            model.addAttribute("message", result.get("message"));
            return "forward:go_update.html";
        }


    }

    @RequestMapping("check.html")
    @ResponseBody
    public Map<String, Object> check(HostIp hostIp) {
        return checkData(hostIp);
    }

    public Map<String, Object> checkData(HostIp hostIp) {
        Map<String, Object> result = new HashMap<>();
        boolean isIp = IpUtil.checkIp(hostIp.getIp());
        if (isIp) {
            result.put("status", false);
            result.put("message", "ip合法");
        } else {
            result.put("message", "非法ip");
            return result;
        }
        Integer checkId = hostService.getHostId(hostIp.getHost(), hostIp.getPort());
        if (checkId != null && checkId != hostIp.getId()) {
            result.put("status", false);
            result.put("message", "当前域名和端口已经占用");
            return result;
        }
        result.put("status", true);
        return result;
    }
}
